package top.techqi.hamtools.widget

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.graphics.Rect
import android.support.v7.app.AlertDialog
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.widget.DatePicker
import android.widget.TabHost
import android.widget.TextView
import android.widget.TimePicker
import top.techqi.hamtools.R
import java.text.SimpleDateFormat
import java.util.*

@Suppress("unused", "MemberVisibilityCanBePrivate", "DEPRECATION")
class Chronos @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : TextView(context, attrs, defStyleAttr), DialogInterface.OnClickListener, DialogInterface.OnDismissListener {
    private val calendar = Calendar.getInstance()

    private lateinit var sdf: SimpleDateFormat
    private var dialog: AlertDialog? = null
    private var datePicker: DatePicker? = null
    private var timePicker: TimePicker? = null

    var format: String = ""
        set(value) {
            field = value
            sdf = SimpleDateFormat(value, Locale.getDefault())
            refreshText()
        }

    var time: Date
        get() = calendar.time
        set(value) {
            calendar.time = value
            refreshText()
        }

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.Chronos)
        format = a.getString(R.styleable.Chronos_format) ?: DEFAULT_FORMAT
        a.recycle()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            requestFocus()
            tryShowDialog()
        }
        return true
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        if (focused) tryShowDialog()
    }

    override fun onClick(dialog: DialogInterface, which: Int) {
        calendar.set(datePicker!!.year, datePicker!!.month, datePicker!!.dayOfMonth,
                timePicker!!.currentHour, timePicker!!.currentMinute, 0)
        refreshText()
    }

    override fun onDismiss(dialog: DialogInterface?) {
        this.dialog = null
    }

    fun setDate(year: Int, month: Int, date: Int, hourOfDay: Int, minute: Int, second: Int) {
        calendar.set(year, month, date, hourOfDay, minute, second)
        refreshText()
    }

    fun setDatet(year: Int, month: Int, date: Int, hourOfDay: Int, minute: Int) {
        calendar.set(year, month, date, hourOfDay, minute)
        refreshText()
    }

    fun setDate(year: Int, month: Int, date: Int) {
        calendar.set(year, month, date)
        refreshText()
    }

    private fun tryShowDialog() {
        if (dialog?.isShowing == true) return

        @SuppressLint("InflateParams")
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_chronos, null)
        with(view.findViewById<TabHost>(R.id.tab)) {
            setup()
            addTab(newTabSpec("data")
                    .setIndicator(context.getString(R.string.dialog_chronos_data))
                    .setContent(R.id.date))
            addTab(newTabSpec("time")
                    .setIndicator(context.getString(R.string.dialog_chronos_time))
                    .setContent(R.id.time))
        }

        with(view.findViewById<DatePicker>(R.id.date)) {
            init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH), null)
            datePicker = this
        }

        with(view.findViewById<TimePicker>(R.id.time)) {
            currentHour = calendar.get(Calendar.HOUR_OF_DAY)
            currentMinute = calendar.get(Calendar.MINUTE)
            setIs24HourView(true)
            timePicker = this
        }

        val builder = AlertDialog.Builder(context)
        builder.setView(view)
        builder.setNegativeButton(android.R.string.cancel, null)
        builder.setPositiveButton(android.R.string.ok, this)
        builder.setOnDismissListener(this)
        dialog = builder.show()
    }

    private fun refreshText() {
        text = sdf.format(calendar.time)
    }

    companion object {
        const val DEFAULT_FORMAT = "yyyy-MM-dd HH:mm"
    }
}